<template>
  <div class="carousel">
    <main class="main">
      <a-tabs :default-active-key="0" @change="tabsChange">
        <a-tab-pane :tab="ele.site" v-for="ele in tabOptions" :key="ele.id">
          <card-list
            @addNew="addNewCarousel"
            @edit="edit"
            @del="del"
            @imgpreview="imgpreview"
            :loading="loading"
            :carouselList="carouselList"
            :carouselGroupList="carouselGroupList"
          ></card-list>
        </a-tab-pane>
      </a-tabs>
    </main>

    <!-- 创建提示框 -->
    <a-modal
      v-model="visible"
      :title="title"
      ok-text="确认"
      cancel-text="取消"
      @ok="confirm"
      @cancel="cancel"
    >
      <!-- 创建轮播图 -->
      <a-form-model :model="form" ref="ruleForm" v-show="!groupSwitch">
        <a-form-model-item label="上传图片" prop="name">
          <template v-if="title == '编辑轮播图'">
            <a-upload
              name="avatar"
              :headers="headers"
              list-type="picture-card"
              class="avatar-uploader"
              :action="uploadUrl"
              :before-upload="beforeUpload"
              @change="handleChange"
              ><img v-if="form.url" :src="form.url" alt="avatar" />
              <div v-else>
                <a-icon :type="photoLoading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">上传</div>
              </div></a-upload
            >
          </template>
          <template v-else>
            <a-upload-dragger
              name="avatar"
              :headers="headers"
              accept="image/*"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="true"
              multiple
              :action="uploadUrl"
              :before-upload="beforeUpload"
              @change="handleChange"
            >
              <div>
                <a-icon :type="photoLoading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">上传</div>
              </div>
            </a-upload-dragger>
          </template>
        </a-form-model-item>
        <a-form-model-item label="分组" required>
          <a-cascader
            :options="carouselGroupList"
            placeholder="请选择"
            @change="onChange"
            v-model="groupValue"
          />
          <a-button type="primary" @click="changeGroup"> 创建分组 </a-button>
        </a-form-model-item>
      </a-form-model>
      <!-- 创建轮播图分组 -->
      <a-form-model :model="groupForm" ref="ruleForm" v-show="groupSwitch">
        <a-form-model-item label="轮播图分组" required>
          <a-input v-model="groupForm.name" placeholder="首页-顶部"></a-input>
        </a-form-model-item>
        <a-button type="primary" @click="changeGroup"> 返回轮播图 </a-button>
      </a-form-model>
    </a-modal>

    <!-- 删除提示框 -->
    <a-modal
      v-model="delVisible"
      title="温馨提示"
      ok-text="确认"
      cancel-text="取消"
      @ok="delConfirm"
    >
      是否删除"{{ currentRecord && currentRecord.id }}"轮播图
    </a-modal>

    <!-- 预览框 -->
    <a-modal
      :visible="previewVisible"
      :footer="null"
      @cancel="previewVisible = false"
      :zIndex="1001"
    >
      <img alt="预览图" style="width: 95%" :src="previewsrc" />
    </a-modal>
  </div>
</template>

<script>
import cardList from '@/pages/components/list/cardList';
import {
  addCarouselApi,
  delCarouselApi,
  getAllCarouselGroupListApi,
  editCarouselApi,
  addCarouselGroupApi,
} from '@/services/webApi/carousel';
import { UPLOAD } from '@/services/webApi/api';
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

export default {
  name: 'carousel',
  components: {
    cardList,
  },
  created() {
    this.uploadUrl = UPLOAD;
    this.headers['authorization'] = JSON.parse(
      localStorage.getItem('user')
    ).token;
    this.getCarousel();
  },
  data() {
    return {
      activeKey: 0,
      groupSwitch: false,
      groupValue: [], //创建选择的分组
      loading: true,
      visible: false,
      delVisible: false,
      imageUrl: '',
      photoLoading: false,
      previewVisible: false,
      form: {
        // 位置id 1:首页
        carouselGroupId: '',
        // 图片数组
        carouselArr: '',
      },
      groupForm: {
        // 轮播图分组
        name: '',
      },
      tabOptions: [
        {
          id: 0,
          site: '全部',
          site_id: 0,
        },
      ],
      carouselGroupList: [],
      // 当前操作行信息
      currentRecord: null,
      uploadUrl: '',
      img: '',
      headers: {},
      title: '',
      carouselList: [],
      listBackup: [],
      previewsrc: '',
      proId: '',
      desc: '为你的网站添加轮播图吧~',
      extraImage:
        'https://gw.alipayobjects.com/zos/rmsportal/RzwpdLnhmvDJToTdfDPe.png',
      // urlList:[]
    };
  },
  methods: {
    imgpreview(src) {
      this.previewsrc = src;
      this.previewVisible = true;
    },
    tabsChange(activeKey) {
      this.activeKey = activeKey;
      if (activeKey === 0) {
        this.carouselList = [...this.listBackup];
      } else {
        let site_id = this.tabOptions[activeKey].site_id;
        this.carouselList = this.listBackup.filter((item) => {
          return item.site_id === site_id;
        });
      }
    },
    changeGroup() {
      this.groupSwitch = !this.groupSwitch;
    },
    // 获取轮播图
    async getCarousel() {
      this.listBackup = [];
      this.carouselList = [];
      this.tabOptions = [
        {
          id: 0,
          site: '全部',
          site_id: 0,
        },
      ];
      getAllCarouselGroupListApi({ limit: 100 }).then((res) => {
        this.carouselGroupList = [];
        res.data.rows.forEach((item) => {
          this.tabOptions.push({
            id: this.tabOptions.length,
            site: item.name,
            site_id: item.id,
          });
          this.carouselGroupList.push({
            value: item.id,
            label: item.name,
          });
          if (item.w_carousels.length) {
            item.w_carousels.forEach((innerItem) => {
              this.listBackup.push({
                classification: item.name,
                url: innerItem.url,
                site_id: innerItem.carouselGroupId,
                id: innerItem.id,
              });
            });
          }
        });

        this.carouselList = [...this.listBackup];
      });
    },
    // 添加轮播图
    addNewCarousel() {
      this.visible = true;
      if (this.tabOptions.length > 1) {
        this.title = '添加轮播图';
        this.form = {
          // 位置id 1:顶部
          site_id: '',
          // 图片
          carouselArr: [],
        };
        this.img = '';
      } else {
        this.title = '添加轮播图分组';
      }
    },
    // 取消创建
    cancel() {
      this.form.carouselArr = [];
      setTimeout(() => {
        this.groupSwitch = false;
      }, 500);
    },
    // 确认创建
    confirm() {
      if (this.groupSwitch) {
        // 创建分组
        addCarouselGroupApi(this.groupForm)
          .then((res) => {
            if (res.code == 200) {
              this.$message.success('创建成功');
            }
            // 更新选项卡分组数据
            this.tabOptions.push({
              id: this.tabOptions.length,
              site: res.data.name,
              site_id: res.data.id,
            });

            // 更新轮播图分组数据
            this.carouselGroupList.push({
              value: res.data.id,
              label: res.data.name,
            });
            this.groupForm.name = '';
            setTimeout(() => {
              this.groupSwitch = false;
              this.form.carouselArr = [];
              location.reload();
            }, 500);
          })
          .catch((err) => {
            this.$message.error(err.msg);
          });
      } else {
        // if (!this.form.carouselArr) {
        //   this.$message.error('请选择图片');
        //   return;
        // }
        if (!this.form.carouselGroupId) {
          this.$message.error('请选择分类');
          return;
        }
        this.visible = false;

        // 创建轮播图
        if (this.title === '添加轮播图') {
          addCarouselApi(this.form)
            .then((res) => {
              this.$message.success(res.msg);
              this.getCarousel();
              console.log(this.urlList);
              // location.reload();
            })
            .catch((err) => {
              this.$message.error(err.msg);
            })
            .finally(() => {
              this.groupValue = [];
            });
        }

        // 更新轮播图
        if (this.title === '编辑轮播图') {
          editCarouselApi(this.form)
            .then((res) => {
              this.$message.success(res.msg);
              this.getCarousel();
              location.reload();
            })
            .catch((err) => {
              this.$message.error(err.msg);
            })
            .finally(() => {
              this.groupValue = [];
            });
        }
      }

      this.currentRecord = null;
      this.groupForm.name = '';
      // location.reload();
    },
    onChange(value) {
      this.form.carouselGroupId = value[0];
    },
    // 删除轮播图
    del(record) {
      this.currentRecord = record;
      this.delVisible = true;
    },
    // 编辑
    edit(record) {
      this.visible = true;
      this.title = '编辑轮播图';
      this.form = {
        id: record.id,
        url: record.url,
        carouselGroupId: record.site_id,
      };
      this.groupValue = [this.form.carouselGroupId];
    },

    delConfirm() {
      delCarouselApi({ id: this.currentRecord.id })
        .then((res) => {
          this.$message.success(res.msg);
          this.getCarousel();
          this.delVisible = false;
        })
        .catch((err) => {
          this.$message.error(err.msg);
          this.delVisible = false;
        });
      this.currentRecord = null;
      this.activeKey = 0;
    },
    // 图片上传
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.photoLoading = true;
        return;
      }
      if (info.file.status === 'done') {
        if (this.title !== '编辑轮播图') {
          this.form.carouselArr.push(info.file.response.path);
        }
        getBase64(info.file.originFileObj, (imageUrl) => {
          this.img = imageUrl;
          this.photoLoading = false;
        });
      }
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/bmp' ||
        file.type === 'image/gif' ||
        file.type === 'image/webp';
      if (!isJpgOrPng) {
        this.$message.error('只能上传图片');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('图片必须小于2MB!');
      }
      return isJpgOrPng && isLt2M;
    },
  },
  watch: {
    /* 重新请求轮播图数据的时候让轮播图渲染列表根据不同分组过滤出来 */
    listBackup: function() {
      if (this.activeKey === 0) {
        this.carouselList = this.listBackup;
      } else {
        // let site_id = this.tabOptions[this.activeKey - 1].site_id;
        // this.carouselList = this.listBackup.filter((item) => {
        //   return item.site_id === site_id;
        // });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.main {
  background-color: #fff;
  padding: 20px;
}
.adminSetCarousel {
  .ant-btn {
    margin-bottom: 20px;
    margin-right: 20px;
  }
  .ant-table-row img {
    width: 120px;
    height: 120px;
    object-fit: contain;
  }
}
.ant-upload {
  width: 200px !important;
  height: 100px !important;
  img {
    width: 100%;
    height: 100%;
  }
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}
.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.list-serach {
  display: flex;
  justify-content: space-around;
  gap: 1rem;
  margin-bottom: 1rem;
}
.ant-modal-body {
  .ant-form-item {
    margin-bottom: 0;
    button {
      margin-top: 20px;
    }
  }
}
</style>
